package com.hsnn.medstgmini.trading.catalog.controller;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicSys;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.trading.catalog.model.form.GoodsSelectForm;
import com.hsnn.medstgmini.trading.catalog.service.PurHospCatalogManager;
import com.hsnn.medstgmini.util.AreaUtil;
import com.hsnn.medstgmini.util.DicSysUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;
import com.hsnn.medstgmini.validator.ValidatorUtil;

/**
 * 
 * @category 医疗机构采购商品目录
 * @author 邱磊
 * @date 2015年6月26日 上午9:37:16
 */
@Controller
@RequestMapping("/purHospCatalog")
public class PurHospCatalogController {
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	private PurHospCatalogManager purHospCatalogManager;
	@Value("#{sysProp['system.delWithHosp']}")
	private boolean delWithHosp;
	@Value("#{sysProp['system.isSetCatalogPrice']}")
	private boolean isSetCatalogPrice;
	
	  
	
	/**
	 * 
	 * @category 医疗机构跳向商品目录勾选页面
	 * @author 邱磊
	 * @date 2015年6月26日 上午10:10:24
	 * @return
	 */
	@RequestMapping("/toGoodsSelect")
	public String toGoodsSelect() {
		List<DicSys> list = DicSysUtil.getDicListByClassCode(Constants.PRO_METHOD);
		List<DicSys> mlist = new ArrayList<DicSys>();
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				DicSys data = list.get(i);
				if (ParseNumber.toInteger(data.getDicCode()) != Constants.GOODS_SOURCE_BACG){
					mlist.add(data);
				}
			}
		}
		request.setAttribute("list", mlist);
		request.setAttribute("isSetCatalogPrice", isSetCatalogPrice);
		return "/pro/pur/goodsSelect";
	}

	/**
	 * 
	 * @category 获取勾选商品目录List
	 * @author 邱磊
	 * @date 2015年6月29日 上午8:18:25
	 * @return
	 */
	@RequestMapping("/getGoodsSelectList")
	@ResponseBody
	public Pagination getGoodsSelectList() {
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		HospInfo hosp = (HospInfo) user.getInfo();
		//int hospClassify = hosp.getHospClassify();
		page.getConditions().put("useRange", String.valueOf(hosp.getHospClassify()) );
		page.setForm(AreaUtil.getSuperArea(hosp.getArea().getAreaid()));
		page.getConditions().put("areaId", hosp.getArea().getAreaid());
		page.getConditions().put("hospCode", hosp.getHospCode());
		page.getConditions().put("projId", request.getParameter("projId"));
		page.getConditions().put("projName", request.getParameter("projName"));
		page.getConditions().put("goodsCode", request.getParameter("goodsCode"));
		page.getConditions().put("qualityspecName", request.getParameter("qualityspecName"));
		page.getConditions().put("drugCode", request.getParameter("drugCode"));
		page.getConditions().put("prodCompname", request.getParameter("prodCompname"));
		page.getConditions().put("goodsSource", request.getParameter("goodsSource"));
		page = purHospCatalogManager.getGoodsSelectList(page);
		return page;
	}

	/**
	 * 
	 * @category 获取修改配送企业列表
	 * @author 邱磊
	 * @date 2015年6月29日 上午9:32:38 
	 * @return
	 */
	@RequestMapping("/getDelCompList")
	@ResponseBody
	public Pagination getDelCompList() {
		Pagination page = new Pagination(request);
		page.getConditions().put("projId", request.getParameter("projId"));
		page.getConditions().put("prodCompCode", request.getParameter("prodCompCode"));
		page.getConditions().put("compCode", request.getParameter("compCode"));
		page.getConditions().put("compName", request.getParameter("compName"));
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		HospInfo sh = (HospInfo) user.getInfo();
		if(!delWithHosp){//商品配送企业地区关系（配送关系）
			page.getConditions().put("goodsCode", request.getParameter("goodsCode"));
			page.setForm(sh);
			purHospCatalogManager.getDelCompListWithGoods(page);
		}else{
			page.getConditions().put("hospCode", sh.getHospCode());
			purHospCatalogManager.getDelCompListWithoutGoods(page);
		}
		return page;
	}

	/**
	 * 
	 * @category 加入勾选目录（医疗机构）
	 * @author 邱磊
	 * @date 2015年6月30日 上午9:21:48
	 * @return
	 */
	@RequestMapping("/saveGoodsSelect")
	@ResponseBody
	public Pagination saveGoodsSelect() {
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		String hospId = ((HospInfo) user.getInfo()).getHospId();
		page.getConditions().put("hospId", hospId);
		page.getConditions().put("goodsCode", request.getParameter("goodsCode"));
		page.getConditions().put("delComp", request.getParameter("delComp"));
		page.getConditions().put("proCount", request.getParameter("proCount"));
		page.getConditions().put("userId", user.getId());
		page = purHospCatalogManager.saveGoodsSelect(page);
		return page;
	}

	/**
	 * 
	 * @category 批量加入所勾选商品目录（医疗机构）
	 * @author 邱磊
	 * @date 2015年6月30日 上午9:21:26
	 * @param array
	 * @return
	 */
	@RequestMapping("/batchSaveGoodsSelect")
	@ResponseBody
	public Pagination batchSaveGoodsSelect(String array) {
		Pagination page = new Pagination(request);
		if (array != null && !"".equals(array)) {
			Gson gson = new Gson();
			Type type = new TypeToken<List<GoodsSelectForm>>() {}.getType();
			List<GoodsSelectForm> list = gson.fromJson(array, type);
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			String hospCode = ((HospInfo) user.getInfo()).getHospCode();
			if (list != null && !list.isEmpty()) {
				for (GoodsSelectForm form : list) {
					if (isSetCatalogPrice){
						if (StringUtils.isNotBlank(form.getProPrice())){
							if (!ValidatorUtil.isDouble(form.getProPrice())){
								page.setSuccess(false);
								page.setMsg("\"" + form.getDrugName() + "\"采购价必须数字！");
								return page;
							} else {
								if (ParseNumber.toDouble(form.getProPrice()) <= 0){
									page.setSuccess(false);
									page.setMsg("\"" +form.getDrugName() + "\"采购价请大于0！");
									return page;
								}
								if (ParseNumber.toDouble(form.getProPrice()) > ParseNumber.toDouble(form.getProLimitPrice())){
									page.setSuccess(false);
									page.setMsg("\"" +form.getDrugName() + "\"采购价不能大于采购限价！");
									return page;
								}
							}
						} else {
							page.setSuccess(false);
							page.setMsg("\"" +form.getDrugName() + "\"采购价不能为空！");
							return page;
						}
					} 
					form.setUpdUser(user.getId());
					form.setHospCode(hospCode);
					
				}
				try {
					purHospCatalogManager.batchSaveGoodsSelect(list);
					page.setSuccess(true);
				} catch (Exception e) {
					e.printStackTrace();
					page.setSuccess(false);
					page.setMsg("操作失败，请联系管理员！");
					return page;
				}
			}
		}
		return page;
	}

	/**
	 * 
	 * @category 跳向已勾选商品目录页面
	 * @author 邱磊
	 * @date 2015年7月7日 上午9:09:33
	 * @return
	 */
	@RequestMapping("/toHaveSelect")
	public String toHaveSelect() {
		return "/pro/pur/purGoodsSelect";
	}

	/**
	 * 
	 * @category 医疗机构获取已勾选目录商品
	 * @author 邱磊
	 * @date 2015年7月7日 上午9:32:53
	 * @return
	 */
	@RequestMapping("/getHaveSelectData")
	@ResponseBody
	public Pagination getHaveSelectData() {
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		String hospCode = ((HospInfo) user.getInfo()).getHospCode();
		page.getConditions().put("hospCode", hospCode);
		page.getConditions().put("projId", request.getParameter("projId"));
		page.getConditions().put("projName", request.getParameter("projName"));
		page.getConditions().put("drugCode", request.getParameter("drugCode"));
		page.getConditions().put("qualityspecName", request.getParameter("qualityspecName"));
		page.getConditions().put("prodCompname", request.getParameter("prodCompname"));
		page.getConditions().put("goodsSource", request.getParameter("goodsSource"));
		page.getConditions().put("status", request.getParameter("status"));
		page.getConditions().put("delComp", request.getParameter("delComp"));
		return purHospCatalogManager.getHaveSelectData(page);
	}
		
	/**
	 * 
	 * @category 修改采购价
	 * @author 邱磊
	 * @date 2015年7月7日 上午10:38:43
	 * @param form
	 * @return
	 */
	@RequestMapping("/modifyData")
	@ResponseBody
	public Pagination modifyData(GoodsSelectForm form) {
		Pagination page = new Pagination(request);
		try {
			if (!ValidatorUtil.validatePositiveNumeric(form.getProPrice())) {
				page.setSuccess(false);
				page.setMsg("请填写正确的价格格式！");
				return page;
			}
			if (StringUtils.isBlank(form.getDelCompId())) {
				page.setSuccess(false);
				page.setMsg("请选择配送企业！");
				return page;
			}
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			form.setUpdUser(user.getId());
			purHospCatalogManager.modifyPrice(form);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("修改出错，请联系管理员！");
		}
		return page;
	}

	/**
	 * 
	 * @category 批量修改采购价和配送企业
	 * @author 邱磊
	 * @date 2015年7月7日 下午2:34:44
	 * @param array
	 * @return
	 */
	@RequestMapping("/batchModifyData")
	@ResponseBody
	public Pagination batchModifyData(String array) {
		Pagination page = new Pagination(request);
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<GoodsSelectForm>>() {
				}.getType();
				List<GoodsSelectForm> list = gson.fromJson(array, type);
				SysUser user = (SysUser) request.getSession().getAttribute(
						Constants.USERINFO);
				if (list != null && !list.isEmpty()) {
					for (GoodsSelectForm form : list) {
						if (isSetCatalogPrice){
							if (StringUtils.isNotBlank(form.getProPrice())){
								if (!ValidatorUtil.isDouble(form.getProPrice())){
									page.setSuccess(false);
									page.setMsg("\"" + form.getDrugName() + "\"采购价必须为数字！");
									return page;
								} else {
									if (ParseNumber.toDouble(form.getProPrice()) > ParseNumber.toDouble(form.getProLimitPrice())){
										page.setSuccess(false);
										page.setMsg("\"" +form.getDrugName() + "\"采购价不能大于采购限价！");
										return page;
									}
								}
							} else {
								page.setSuccess(false);
								page.setMsg("\"" +form.getDrugName() + "\"采购价不能为空！");
								return page;
							}
							
						} else {
							form.setProPrice(null);
						}
						form.setUpdUser(user.getId());
					}
					purHospCatalogManager.batchModifyData(list, user);
					page.setSuccess(true);
				}
			} else {
				page.setSuccess(false);
				page.setMsg("请选择要修改的商品！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("修改出错，请联系管理员！");
			return page;
		}
		return page;
	}

	/**
	 * 
	 * @category 批量启用停用
	 * @author 邱磊
	 * @date 2015年7月7日 上午11:00:44
	 * @param array
	 * @return
	 */
	@RequestMapping("/batchSwitchStatus")
	@ResponseBody
	public Pagination batchSwitchStatus(String array) {
		Pagination page = new Pagination(request);
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<GoodsSelectForm>>() {
				}.getType();
				List<GoodsSelectForm> list = gson.fromJson(array, type);
				SysUser user = (SysUser) request.getSession().getAttribute(
						Constants.USERINFO);
				if (list != null && !list.isEmpty()) {
					for (GoodsSelectForm dp : list) {
						dp.setUpdUser(user.getId());
				}
				purHospCatalogManager.batchSwitchStatus(list);
				page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * 
	 * @category 弹窗页面
	 * @Auther 徐国鹏
	 * @date 2015年7月7日 下午12:04:03
	 * @return
	 * @return String
	 */
	@RequestMapping("/examplest1")
	public String toexamplest(){
		return "/pro/pur/examplest";
	}
	
	/**
	 * @category 根据商品编码获取所有配送企业
	 * @author 韩守松
	 * @date   2015年12月8日
	 * @param  @return
	 */
	@RequestMapping("/getAllDelByGoodsCode")
	@ResponseBody
	public Pagination getAllDelByGoodsCode(){
		Pagination page = new Pagination(request);
		page.getConditions().put("projId", request.getParameter("projId"));
		page.getConditions().put("prodCompCode", request.getParameter("prodCompCode"));
		page.getConditions().put("compCode", request.getParameter("compCode"));
		page.getConditions().put("compName", request.getParameter("compName"));
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		HospInfo sh = (HospInfo) user.getInfo();
		/*if(!delWithHosp){//商品配送企业地区关系（配送关系）
			page.getConditions().put("goodsCode", request.getParameter("goodsCode"));
			page.setForm(sh);
			purHospCatalogManager.getDelCompListWithGoods(page);
		}else{*/
		    page.getConditions().put("goodsCode", request.getParameter("goodsCode"));
		    page.getConditions().put("areaCode", sh.getArea().getAreaid());
			//page.getConditions().put("hospCode", sh.getHospCode());
			purHospCatalogManager.getAllDelByGoodsCode(page);
		//}
		return page;
	}
	
	/**
	 * @category 保存新增的配送关系
	 * @author 韩守松
	 * @date   2015年12月8日
	 * @param  @param array
	 * @param  @return
	 */
	@RequestMapping("/goodsWithDelSave")
	@ResponseBody
	public Pagination goodsWithDelSave(String array) {
		Pagination page = new Pagination(request);
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<GoodsSelectForm>>() {
				}.getType();
				List<GoodsSelectForm> list = gson.fromJson(array, type);
				SysUser user = (SysUser) request.getSession().getAttribute(
						Constants.USERINFO);
				if (list != null && !list.isEmpty()) {
					for (GoodsSelectForm form : list) {
						if (isSetCatalogPrice){
							if (StringUtils.isNotBlank(form.getProPrice())){
								if (!ValidatorUtil.isDouble(form.getProPrice())){
									page.setSuccess(false);
									page.setMsg("\"" + form.getDrugName() + "\"采购价必须为数字！");
									return page;
								} else {
									if (ParseNumber.toDouble(form.getProPrice()) > ParseNumber.toDouble(form.getProLimitPrice())){
										page.setSuccess(false);
										page.setMsg("\"" +form.getDrugName() + "\"采购价不能大于采购限价！");
										return page;
									}
								}
							} else {
								page.setSuccess(false);
								page.setMsg("\"" +form.getDrugName() + "\"采购价不能为空！");
								return page;
							}
							
						} else {
							form.setProPrice(null);
						}
						form.setUpdUser(user.getId());
					}
					purHospCatalogManager.goodsWithDelSave(list, user);
					page.setSuccess(true);
				}
			} else {
				page.setSuccess(false);
				page.setMsg("请选择要修改的商品！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("修改出错，请联系管理员！");
			return page;
		}
		return page;
	}
	
	
	/**
	 * 
	 * @category 批量修改采购目录表配送企业
	 * @author lil
	 * @date 2015年12月13日
	 * @param array
	 * @return
	 */
	@RequestMapping("/batchModifyCgmlZx")
	@ResponseBody
	public Pagination batchModifyCgmlZx(String array) {
		Pagination page = new Pagination(request);
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<GoodsSelectForm>>() {
				}.getType();
				List<GoodsSelectForm> list = gson.fromJson(array, type);
				SysUser user = (SysUser) request.getSession().getAttribute(
						Constants.USERINFO);
				if (list != null && !list.isEmpty()) {
					purHospCatalogManager.batchModifyCgmlZx(list, user);
					page.setSuccess(true);
				}
			} else {
				page.setSuccess(false);
				page.setMsg("请选择要修改的商品！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("修改出错，请联系管理员！");
			return page;
		}
		return page;
	}
	
	/**
	 * 
	 * @category 根据主键编号删除采购目录数据
	 * @author lil
	 * @date 2015年12月18日
	 * @param array
	 * @return
	 */
	@RequestMapping("/deleteHospcatalog")
	@ResponseBody
	public Pagination deleteHospcatalog(String array) {
		Pagination page = new Pagination(request);
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<GoodsSelectForm>>() {
				}.getType();
				List<GoodsSelectForm> list = gson.fromJson(array, type);
				if (list != null && !list.isEmpty()) {
					purHospCatalogManager.deleteHospcatalog(list);
					page.setSuccess(true);
				}
			} else {
				page.setSuccess(false);
				page.setMsg("请选择要删除的商品！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMsg("修改出错，请联系管理员！");
			return page;
		}
		return page;
	}
}
